<?php
/**
 * Created by PhpStorm.
 * User: khanhht
 * Date: 6/30/14
 * Time: 3:28 PM
 */

class AuthController extends Zend_Controller_Action {

    public function init(){
        
    }

    
    public function loginAction(){
        $request = $this->getRequest();
        $form = new Default_Form_Login();
        $db = Zend_Db_Table::getDefaultAdapter();
        $flash = $this->_helper->getHelper('FlashMessenger');
        if($request->isPost()){
            $formData = $request->getPost();
            if($form->isValid($formData)){
                $adapter = new Zend_Auth_Adapter_DbTable($db,'admin','username','password','MD5(?)');
                $adapter->setIdentity($form->getValue('username'));
                $adapter->setCredential($form->getValue('password'));
                $auth = Zend_Auth::getInstance();
                $auth->setStorage(new Zend_Auth_Storage_Session(SESSION_NAMESPACE));
                $result = $auth->authenticate($adapter);
                if ($result->isValid())
                {
                    $userModel = new Default_Model_Admin();
                    $userInfo = $userModel->getDataByUsername($form->getValue('username'));
                    $auth->getStorage()->write(array(
                        'username' => $userInfo->username,
                        'adminId' => $userInfo->adminId));
                    $session = new Zend_Session_Namespace(SESSION_NAMESPACE);
                    $session->setExpirationSeconds(60*60*24);
                   
                    $redirectUrl        = $this->getRequest()->getParam('redirectUrl', '');
                    if($redirectUrl != ''){
                        $this->_redirect($redirectUrl);
                    }else{
                        $this->_helper->redirector('index','index');
                    }
                }
            }

        }
        $this->view->messages = $flash->getMessages();
        $this->view->loginForm = $form;
    }

    public function logoutAction(){
        $this->_helper->layout()->disableLayout(true);
        $this->_helper->viewRenderer->setNoRender(true);
        $a = My_Acl::logout('Zend_Auth_KPI_ASMEMBER');
        if($a){
            $this->_helper->redirector('index', 'user', 'admin');
            exit;
        }
        My_Acl::logout();
        $this->_helper->redirector('login', 'auth', 'default');
        exit;
    }

} 